﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Common.ECS
{
    public class Context<TEntity> : IContext<TEntity> where TEntity:IEntity
    {
        /// <summary> 通过匹配器匹配出来的群组</summary>
        private Dictionary<IMatcher<TEntity>, IGroup<TEntity>> matcher2Groups = new Dictionary<IMatcher<TEntity>, IGroup<TEntity>>();

        public Dictionary<ComponentType, List<IComponent>> Components = new Dictionary<ComponentType, List<IComponent>>();

        public Dictionary<int, TEntity> AllEntities
        {
            get
            {
                return entities;
            }
        }

        public Dictionary<Type, List<IComponent>> System2Components = new Dictionary<Type, List<IComponent>>();
        
        protected Dictionary<int, TEntity> entities = new Dictionary<int, TEntity>();

        public virtual TEntity CreateEntity()
        {
            TEntity entity;
            entity = (TEntity)Activator.CreateInstance(typeof(TEntity));
            entity.Init();
            foreach (var item in entity.Components)
            {
                if (!Components.ContainsKey(item.Key))
                {
                    Components.Add(item.Key, new List<IComponent>() { item.Value });
                }
                else
                {
                    Components[item.Key].Add(item.Value);
                }
            }

            entities.Add(entity.EntityID,entity);
            return entity;
        }

        public virtual TEntity GetEntityByID(int entityID)
        {
            for (int i = 0; i < entities.Count; i++)
            {
                if (entities[i].EntityID == entityID)
                {
                    return entities[i];
                } 
            }
            return default(TEntity);
        }

    }
}
